console.log('init contentScript')

chrome.runtime.onMessage.addListener(onRuntimeMessage)


import {bossService} from '../crawl-scripts/boss'

import {zhilianService} from '../crawl-scripts/zhilian'
import {qianchengService} from '../crawl-scripts/51job'
import {liepinService} from '../crawl-scripts/liepin'


// 监听runtime消息
function onRuntimeMessage(request, sender, sendResponse) {
    // Tips: 需要sendResponse,不然可能会阻塞其他消息
    // console.log('back---',request,sender);
    // sendResponse()
    switch (request.action) {
        case "getPageHtml":
            // console.log($util.htmlToString(document));
            sendResponse($util.htmlToString(document))
            break;
        case "collection":
            collection(sendResponse)
            break;
        default:
            // console.warn("Invalid message", data);
            sendResponse('Invalid message')
    }
}

/*
*    猎聘
     boss
     领英
     51job
     智联
* */
const getCollection = () => {
    let host = window.location.host;
    let enums = [
        //  测试
        {
            domain: 'localhost',
            collection: () => bossService.collection()
        },
        // 猎聘
        {
            domain: 'h.liepin',
            collection: () => liepinService.collection()
        },
        // boss
        {
            domain: '.zhipin.com',
            collection: () => bossService.collection()
        },
        //  领英 暂时不做
        // {
        //     domain: 'linkedin',
        //     collection: () => linkedinService.get_result()
        // },
        //   51job
        {
            domain: '.51job.com',
            collection: () => qianchengService.collection()
        },
        //  智联
        {
            domain: '.zhaopin.com',
            collection: () => zhilianService.collection()
        }
    ]

    let domainInfo = enums.find(item => host.includes(item.domain))

    return domainInfo ? domainInfo.collection : false
}

const collection = (sender) => {
    try {
        const collection = getCollection()

        if (collection) {
            let data = collection()
            console.log('采集结果--', data);
            sender({
                status: 0,
                data
            })
        } else {
            sender({
                status: 1,
                message: '暂不支持该网站！'
            })
        }
    } catch (e) {
        console.log('error--', e);
        sender({
            status: 1,
            message: '采集失败，请联系管理员！'
        })
    }

}
